package fi.aalto.cse.T110_5150.P2PClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

public final class MessageHeader {
	private static long messageSequenceNumber = 0;
	
	public int version;
	public int ttl;
	public int messageType;
	public int reserved;
	
	public int originalPort;
	public int length;
	
	public byte[] originalAddress = new byte[4];
	public int messageId;
	
	@Override
	public String toString() {
		return String.format("messageType=%d, length=%d, ttl=%d", messageType, length, ttl);
	}
	
	public static MessageHeader create(int messageType, int ttl, int length) {
		return create(generateMessageId(), messageType, ttl, length);
	}
	
	public static MessageHeader create(int messageId, int messageType, int ttl, int length) {
		MessageHeader header = new MessageHeader();
		header.version = P2PHelper.VERSION_CURRENT;		
		header.ttl = ttl;
		header.messageType = messageType;
		header.reserved = 0;		

		header.originalPort = LocalPeer.getInstance().getAddress().getPort();
		header.length = length;

		header.originalAddress = LocalPeer.getInstance().getAddress().getAddressBytes();

		header.messageId = messageId;
		return header;
	}
	
	public PeerAddress getOriginalPeerAddress() throws UnknownHostException {
		return new PeerAddress(InetAddress.getByAddress(originalAddress), originalPort);
	}
	
	
	public static int generateMessageId() {
		String s = String.format("%s%d%d", LocalPeer.getInstance(), System.currentTimeMillis(),
				messageSequenceNumber++);
		return P2PHelper.getHashValue(s);
	}
}
